﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TimeAlert
{
    public class Helper
    {
        public static DataTable ExamToDataTable<T>(List<ExamDto> list)
        {
            DataTable dt = new DataTable();
            if (list == null || list.Count == 0)
                return dt;

            dt.Columns.Add("Id");
            dt.Columns.Add("ExamName");
            dt.Columns.Add("StartTime");
            dt.Columns.Add("EndTime");
            // 2. 将 List 中的数据添加到 DataTable 行
            foreach (ExamDto item in list)
            {
                DataRow row = dt.NewRow();
                row["Id"] = item.Id;
                row["ExamName"] = item.ExamName;
                row["StartTime"] = item.StartTime.ToString("yyyy-MM-dd HH:mm");
                row["EndTime"] = item.EndTime.ToString("yyyy-MM-dd HH:mm");

                dt.Rows.Add(row);
            }

            return dt;
        }

        public static void SaveExamList<T>(object obj)
        {
            DataTable dt = obj as DataTable;
            List<Exam> list = new List<Exam>();
            if (dt == null)
                return;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Exam e = new Exam();

                e.Id = dt.Rows[i]["Id"]?.ToString() ?? string.Empty;
                e.ExamName = dt.Rows[i]["ExamName"]?.ToString() ?? string.Empty;
                e.StartTime = DateTime.Parse(dt.Rows[i]["StartTime"]?.ToString());
                e.EndTime = DateTime.Parse(dt.Rows[i]["EndTime"]?.ToString());
                list.Add(e);
            }
            Business.WriteExamInfo(list);
        }

        /// <summary>
        /// 将 List<T> 转换为 DataTable
        /// </summary>
        public static DataTable ListToDataTable<T>(List<T> list)
        {
            DataTable dt = new DataTable();
            if (list == null || list.Count == 0)
                return dt;

            // 1. 获取实体类的所有属性，作为 DataTable 的列
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                // 添加列（列名=属性名，类型=属性类型）
                dt.Columns.Add(prop.Name, prop.PropertyType);
            }

            // 2. 将 List 中的数据添加到 DataTable 行
            foreach (T item in list)
            {
                DataRow row = dt.NewRow();
                foreach (PropertyInfo prop in props)
                {
                    // 为每行赋值（属性值=单元格值）
                    row[prop.Name] = prop.GetValue(item, null) ?? DBNull.Value;
                }
                dt.Rows.Add(row);
            }

            return dt;
        }
    }
}
